import '../dao/ImDepartmentDao.dart';
import '../pojo/ImPojo.dart';
import '../socket/dto/business/PullData.dart';
import 'BaseService.dart';

class ImDepartmentService extends BaseService {

   Future<void> saveOrUpdates(String userId, List<DepartmentInfoItem> departmentInfoItems) async {
    if (departmentInfoItems.isEmpty) return;

    ImDepartmentDao imDepartmentDao = ImDepartmentDao();
    List<ImDepartment> departments = departmentInfoItems.map((item){return _toImDepartment(userId, item);}).toList();

    List<String> codeList = departmentInfoItems.map((e) => e.orgCode).toList();
    List dbDepartments = await imDepartmentDao.getByIds(codeList);
    Set<dynamic> dbCodeSet = dbDepartments.map((e) => e['code']).toSet();
    List<ImDepartment> newDepartments = departments.where((d) => !dbCodeSet.contains(d.code)).toList();
    List<ImDepartment> updateDepartments = departments.where((d) => dbCodeSet.contains(d.code)).toList();

    await imDepartmentDao.inserts(newDepartments);
    await imDepartmentDao.updates(updateDepartments);
  }

  ImDepartment _toImDepartment(String userId, DepartmentInfoItem item) {
    return ImDepartment(currentUserId: userId, code: item.orgCode, name: item.departmentName, description: item.desc,
        parentCode: item.parentCode, managerUserId: item.managerUserId,
        otherManagerUserIds: item.otherManagerUserIdList?.join(','),
        status: ImDepartmentStatus.ofValue(item.status?.value));
  }
}